from rest_framework.response import Response
from rest_framework.views import APIView
from django.conf import settings
from user.models import UserInfo
import os,random

class UploadAvatarView(APIView):

    def post(self, request):
        username = request.data.get('username')
        # 获取上传的文件
        file_obj = request.FILES.get('file')
        file_name = str(random.random()).split('.')[1] + '.' + str(file_obj.name).split('.')[1]
        current_path = os.path.join('media', 'userAvatar', file_name)  # 当前文件存放的路径
        try:
            with open(current_path, 'wb') as f:
                for i in file_obj.chunks():  # 循环接受文件块
                    f.write(i)
        except Exception as e:
            res = {'code': 500, 'msg': '%s' %e}
            return Response(res)

        scheme = request.scheme
        host = request.get_host()
        full_url = f"{scheme}://{host}/media/userAvatar/{file_name}"
        #更新用户上传的头像到数据库
        UserInfo.objects.filter(username=username).update(
            avatar=full_url
        )
        user_obj = UserInfo.objects.get(username=username)
        avatar = user_obj.avatar

        res = {'code': 200, 'avatar': avatar, 'msg': '更新成功'}
        return Response(res)